/***
 * Copyright (c) 2021-2031 murenchao
 * fig is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.software.fig.mqtt.client.paho

import cool.taomu.software.fig.mqtt.client.paho.inter.IMQTTSubscriber
import io.netty.handler.codec.mqtt.MqttQoS
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence
import org.eclipse.xtend.lib.annotations.Accessors

@Accessors
class MQTTSubscriber implements IMQTTSubscriber {
	String username;
	String password;
	int timeout;
	int keepAlive;
	String clientId;
	String ip;
	int port = 1883;
	MqttQoS qos;
	String topics;
	boolean cleanSession = false;
	CallbackTemplate callback;
	boolean isSsl = false;

	new(String username, String password, int timeout, int keepAlive, String clientId, String ip,int port,MqttQoS qos,
		String topics,boolean cleanSession, CallbackTemplate callback) {
		    this(username,password,timeout,keepAlive,clientId,ip,port,qos,topics,cleanSession,false,callback);
	}
	
	new(String username, String password, int timeout, int keepAlive, String clientId, String ip,int port,MqttQoS qos,
        String topics,boolean cleanSession,boolean isSsl, CallbackTemplate callback) {
        this.username = username;
        this.password = password;
        this.timeout = timeout;
        this.keepAlive = keepAlive;
        this.clientId = clientId;
        this.ip = ip;
        this.port = port;
        this.qos = qos;
        this.topics = topics;
        this.cleanSession = cleanSession;
        this.callback = callback;
        this.isSsl = isSsl;
    }

	override subscriber() {
		val memoryPersistence = new MemoryPersistence();
		var mqttConnectOptions = new MqttConnectOptions();
		mqttConnectOptions.setCleanSession(cleanSession);
		mqttConnectOptions.setUserName(username);
		mqttConnectOptions.setPassword(password.toCharArray());
		mqttConnectOptions.setConnectionTimeout(timeout);
		mqttConnectOptions.setKeepAliveInterval(keepAlive);
		var broker = String.format("%s://%s:%d",this.isSsl ? "ssl" : "tcp",this.ip,this.port);
		val mqttClient = new org.eclipse.paho.client.mqttv3.MqttClient(broker, clientId, memoryPersistence);
		this.callback.client = mqttClient;
		this.callback.options = mqttConnectOptions;
		mqttClient.setCallback(callback);
		mqttClient.connect(mqttConnectOptions);
		mqttClient.subscribe(topics, qos.value);
		Runtime.runtime.addShutdownHook(new Thread(){
			override run(){
				mqttClient.disconnect;
				memoryPersistence.close;
			}
		})
	}

	override run() {
		subscriber();
	}

}
